<?php
namespace app\index\controller;

use think\Controller;

class Goods extends Controller
{

    private $user_id;

    public function _initialize()
    {
        $user_id = is_login('user_id');
        if ($user_id) {
            $this->user_id = $user_id;
        } else {
            return $this->error('尚未登录，即将跳至登录页...', url('auth/login'));
        }
    }

    /**
     * 我的二手货页面
     * @author 杨栋森 mutoe@foxmail.com at 2016-07-23
     */
    public function goodsList()
    {
        $param = input('param.');

        $goods = model('Goods');
        $goods->where(['user_id' => $this->user_id]);

        // 排序规则
        switch (@$param['sort']) {
            case 'deadline':
                $sort = 'deadline';
                $goods->order('deadline');
                break;
            case 'hits':
                $sort = 'hits';
                $goods->order('hits desc');
                break;
            case 'time':
                $sort = 'time';
                $goods->order('create_time desc');
                break;
            default:
                $sort = 'deadline';
                $goods->order('deadline');
        }

        // 分页显示
        $goods_list = $goods->paginate(config('goods.paginate'));

        return view('', ['data' => $goods_list, 'sort' => $sort]);
    }

    /**
     * 添加货物
     * @author 杨栋森 mutoe@foxmail.com at 2016-07-20
     *
     * TODO: 整合编辑货物方法
     */
    public function addGoods()
    {
        if (request()->isGet()) {
            return view('');
        }
        if (request()->isPost()) {
            $data = input('post.');

            // 字段验证
            $validate = validate('Goods');
            if (!$validate->check($data)) {
                return $this->error($validate->getError());
            }

            // 附加提示语
            $extra_message = "";

            // 过滤图片展示字段
            $file_uri_array = [];
            $photo = json_decode($data['photo']);
            unset($data['photo']);
            foreach ($photo as $key => $value) {
                if ($key == "length") {
                    continue;
                }

                // 去除二级根目录前缀
                if ($subroot = config('subroot')) {
                    $foo = explode('/', $subroot);
                    $subroot = array_pop($foo);
                    $value = preg_replace('@/' . $subroot . '@i', '', $value);
                }
                $file_uri_array[] = $value;
            }
            if (!empty($file_uri_array)) {
                // 归档图片
                $new_uri_array = $this->archivePhotos($file_uri_array);
                $error_list = [];
                foreach ($new_uri_array as $key => $new_uri) {
                    if ($new_uri == false) {
                        $error_list[] = $file_uri_array[$key];
                        unset($new_uri_array[$key]);
                    }
                }
                $expand = [
                    'photos' => $new_uri_array,
                    'photos_count' => count($new_uri_array),
                ];
                $data['expand'] = json_encode($expand);

                // 添加第一张图片作为缩略图
                $data['thumb'] = $new_uri_array[0];

                // 如果新数组为空 添加提示语
                if (count($error_list) > 0) {
                    $extra_message .= "，但这些图片好像没有添加上，请返回编辑页面重新添加图片" . $error_list;
                }
            }

            // 数据写入
            $goods = model('Goods');
            $goods->data($data);
            if (!$goods->allowField(true)->save()) {
                return $this->error($goods->getError());
            }
            // TODO: 跳转至货物详情页面
            return $this->success("添加成功" . $extra_message);
        }
    }

    /**
     * 归档图片
     * 按月份将货物展示图片归档
     * @author 杨栋森 mutoe@foxmail.com at 2016-07-21
     *
     * @param  array  $file_uri_array   图片相对路径数组(相对web根目录)
     * @return array  返回结果路径数组(相对web根目录) 空文件返回null, 移动失败返回false
     */
    private function archivePhotos($file_uri_array)
    {
        $result = [];
        // 获取存储目录
        $target_path = config('upload_path.photo');
        // 获取当前月份
        $month = date('Ym', time());
        foreach ($file_uri_array as $file_uri) {
            // 如果是空值 在返回结果中插入null
            if (empty($file_uri)) {
                $result[] = null;
                continue;
            }

            // 生成12位摘要文件名
            $new_name = substr(md5(time() . $file_uri), 0, 12);
            // 取得文件后缀
            $foo = explode(".", $file_uri);
            $ext = array_pop($foo);
            $new_name .= '.' . $ext;

            // 建立归档文件夹
            $root = dirname($_SERVER['SCRIPT_FILENAME']);
            $new_path = $target_path . "/" . $month;
            $real_path = $root . $new_path;
            if (!file_exists($real_path)) {
                mkdir($real_path);
            }

            // 检查源文件是否存在
            if (!file_exists($root . $file_uri)) {
                $result[] = false;
                continue;
            }

            // 移动文件
            if (rename($root . $file_uri, $real_path . "/" . $new_name)) {
                $result[] = $new_path . "/" . $new_name;
            } else {
                $result[] = false;
            }
        }
        return $result;
    }

}
